package Volume1.ch5;

import java.util.Random;

/**
 * 5.7 反射demo
 */
public class ReflectionDemo {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Employee employee = new Employee("hacker");
        System.out.println("=======demo2测试===========");
        System.out.println(employee.getClass().getName() + " " + employee.getEmpName());

        System.out.println("=======demo2测试begin===========\n" +
                "区分getClass和getName的用途\n" +
                "运算结果：");
        Random generator = new Random();
        Class cl = generator.getClass();
        System.out.println("cl = " + cl);
        String name = cl.getName();
        System.out.println("name = " + name);
        System.out.println("=======demo2测试end============\n");

        System.out.println("=======demo3测试begin===========\n" +
                "通过静态方法forName获得类名对应的class对象");
        Class className = Class.forName(name);
        System.out.println(className);
        System.out.println("=======demo3测试end============\n");

        System.out.println("=======demo4测试begin===========\n" +
                "通过.class获取Class类对象的");
        Class aClass = Random.class;
        System.out.println(aClass);
        Class bClass = int.class;
        System.out.println(bClass);
        System.out.println("=======demo4测试end============\n");

        System.out.println("=======demo5测试begin==========\n" +
                "要点：虚拟机为每个类管理一个Class对象，可以用==来实现两个对象的比较操作");
        if (employee.getClass() == Employee.class) {
            System.out.println("employee.getClass() == Employee.class");
        }
        System.out.println("=======demo5测试end============\n");


        System.out.println("=======demo6测试begin==========\n" +
                "要点：通过newInstance动态创建一个类的实例");
        Employee newInstance = employee.getClass().newInstance();
        newInstance.setEmpName("jacob");
        System.out.println(newInstance.getClass() + " " + newInstance.getEmpName());
        System.out.println("=======demo6测试end============\n");

        System.out.println("=======demo7测试begin==========\n" +
                "要点：通过forName与newInstance配合使用，可以根据存储在字符串终端类名创建一个对象");
        Object o = Class.forName(name).newInstance();//name = ava.util.Random
        System.out.println(o.getClass());
        System.out.println("=======demo7测试end============\n");


    }

}

class Employee {
    private String empName;

    public Employee() {
    }

    public Employee(String empName) {
        this.empName = empName;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }
}